import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:jyofservice/bean/check_list_entity.dart';
import 'package:jyofservice/util/Image_picked.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:uuid/uuid.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../util/AssetPicker.dart';

class DealJiCha extends StatefulWidget {
  CheckListEntity? checkListEntity;
  DealJiCha({this.checkListEntity});

  @override
  _DealJiChaState createState() => _DealJiChaState();
}

class _DealJiChaState extends State<DealJiCha> {
  TextEditingController _jiChaTextEditingController =
      new TextEditingController();
  String? personName;
  String? chuLiJieGuo;
  int? personId;
  late SharedPreferences sharedPreferences;
  String? key;
  var jiChaDate = "";

  //记录从相册选择的附件图片
  List<String> _imageUrlsEdit = [];
  String _path = '';
  bool isloading = true;

  //获取当前时间
  var dateTime = new DateTime.now();

  //工单状态
  var _state = "";

  //标题背景色
  Color? color;
  final int maxAssetsCount = 9;
  bool isDisplayingDetail = true;

  List<AssetEntity> assets = <AssetEntity>[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //默认日期显示
    jiChaDate = dateTime.toString().substring(0, 19);
    color = Color(0xffe23e51);
    //获取地址
    _getPath();
  }

  //获得应用文档目录
  Future _getPath() async {
    sharedPreferences = await SharedPreferences.getInstance();
    final Directory _directory = await getApplicationDocumentsDirectory();
    final Directory _imageDirectory =
        await new Directory('${_directory.path}/image/')
            .create(recursive: true);
    _path = _imageDirectory.path;
    print('本次获得路径：${_imageDirectory.path}');
    return _path;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        Navigator.pop(context, false);
        return Future.value(false);
      },
      child: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: Text('稽查处理',
                style: TextStyle(
                    color: Colors.white, fontSize: ScreenUtil().setSp(45))),
            leading: IconButton(
                icon: Icon(Icons.arrow_back_ios),
                onPressed: () {
                  if (isloading) {
                    //清空材料明细
                    Navigator.pop(context, false);
                  } else {
                    Fluttertoast.showToast(msg: "正在提交,请稍后退出...");
                  }
                }),
          ),
          body: Column(
            children: <Widget>[
              Expanded(
                child: Stack(
                  children: <Widget>[
                    SingleChildScrollView(
                      child: Column(
                        children: <Widget>[
                          Container(
                            color: color,
                            width: ScreenUtil().screenWidth,
                            height: ScreenUtil().setHeight(100),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                                SizedBox(
                                  width: ScreenUtil().setWidth(30),
                                ),
                                Text("采暖年度 ${dateTime.year}",
                                    style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        color: Colors.white,
                                        fontSize: ScreenUtil().setSp(40))),
                                Expanded(
                                  flex: 1,
                                  child: SizedBox(),
                                ),
                                Icon(
                                  Icons.access_time,
                                  color: Colors.white,
                                ),
                                Text(_state ?? '',
                                    style: TextStyle(
                                        fontWeight: FontWeight.w600,
                                        color: Colors.white,
                                        fontSize: ScreenUtil().setSp(40))),
                                SizedBox(
                                  width: ScreenUtil().setWidth(30),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            height: ScreenUtil().setHeight(70),
                            padding: EdgeInsets.fromLTRB(10.0, 10.0, 0, 0),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: <Widget>[
                                Icon(
                                  Icons.person,
                                  color: Colors.blue,
                                ),
                                Text(
                                  '用户信息',
                                  style: TextStyle(
                                      color: Colors.blue,
                                      fontSize: ScreenUtil().setSp(40)),
                                ),
                              ],
                            ),
                          ),
                          getRow("用户编码", widget.checkListEntity!.ybbm ?? ""),
                          getRow("用户姓名", widget.checkListEntity!.lxr ?? ""),
                          getPhoneRow(
                              "联系电话", widget.checkListEntity!.lxdh ?? ""),
                          getRow("用户地址", widget.checkListEntity!.yhmc ?? ""),
                          SizedBox(
                            child: Container(
                              color: Color(0xfff1f1f1),
                            ),
                            height: ScreenUtil().setHeight(25.0),
                          ),
                          Container(
                            child: Column(
                              children: <Widget>[
                                //稽查日期
                                //getCaiNuanTime(),
                                Container(
                                  height: 1.0,
                                  margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  color: Color(0xffeeeeee),
                                ),
                                getShiFouChuLi(),
                                Container(
                                  height: 1.0,
                                  margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  color: Color(0xffeeeeee),
                                ),
                                //稽查备注
                                getJiChaBeiZhu(),
                                Container(
                                  height: 1.0,
                                  margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  color: Color(0xffeeeeee),
                                ),
                                SizedBox(
                                    height: 10.0,
                                    child: Container(
                                      color: Colors.black12,
                                    )),
                                //添加图片视图
                                JhAssetPicker(
                                  assetType: AssetTypes.image,
                                  lineCount: 3,
                                  callBack:
                                      (assetEntityList, CallBackType type) {
                                    if (type == CallBackType.add) {
                                      Navigator.pop(context);
                                    }
                                    print('assetEntityList-------------');
                                    print(assetEntityList);
                                    print('assetEntityList-------------');

                                    assets = assetEntityList;
                                    if (mounted) {
                                      setState(() {});
                                    }
                                  },
                                ),
                                // IconButton(
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    Offstage(
                      offstage: isloading,
                      child: SpinKitFadingCircle(
                        color: Colors.blue,
                        size: 50.0,
                      ),
                    )
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(
                    10, 0, 10, ScreenUtil().bottomBarHeight + 20),
                width: ScreenUtil().screenWidth,
                child: Row(
                  children: <Widget>[
                    Expanded(
                        child: Container(
                            height: ScreenUtil().setHeight(100),
                            color: Colors.blue,
                            child: TextButton(
                              child: Text(
                                "立即提交",
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil().setSp(38)),
                              ),
                              onPressed: () {
                                chuLiGongDan();
                              },
                            )))
                  ],
                ),
              ),
            ],
          )),
    );
  }


  //是否处理
  Widget getShiFouChuLi() {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '稽查结果',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(50),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
//              height: ScreenUtil().setHeight(80),
              //1.用DropdownButtonHideUnderline包裹DropdownButton 取消下划线
              child: DropdownButton(
                underline: new Container(),
                //2.取消下划线
                isExpanded: true,
                value: chuLiJieGuo,
                items: getListData(),
                hint: Text('请选择',
                    style: TextStyle(
                        color: Color(0xFFB6B6B6),
                        fontSize: ScreenUtil().setSp(30))),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      chuLiJieGuo = T;
                    });
                  }

                },

                icon: Icon(Icons.keyboard_arrow_right),
                style: new TextStyle(
                    //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          ),
        ],
      ),
    );
  }

  List<DropdownMenuItem> getListData() {
    List<DropdownMenuItem> items = [];
    DropdownMenuItem dropdownMenuItem1 = new DropdownMenuItem(
      child: new Text('异常', style: TextStyle(fontSize: ScreenUtil().setSp(35))),
      value: '异常',
    );
    items.add(dropdownMenuItem1);
    DropdownMenuItem dropdownMenuItem2 = new DropdownMenuItem(
      child: new Text('通过', style: TextStyle(fontSize: ScreenUtil().setSp(35))),
      value: '通过',
    );
    items.add(dropdownMenuItem2);
    //待复核

    return items;
  }

  //稽查处理
  chuLiGongDan() {
    if(chuLiJieGuo==null) {
        Fluttertoast.showToast(
          msg: "请选择稽查结果",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );
        return;
    }
    if(mounted) {
      setState(() {
        isloading= false;
      });
    }
    if(_imageUrlsEdit.length>0){
      submitFile();
    }else{
      submitInfo("");
    }

  }

  //稽查时间
  Widget getCaiNuanTime() {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            "稽查日期",
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: Container(
              padding: EdgeInsets.all(2),
//              height: ScreenUtil().setHeight(80),
              child: Row(
                children: <Widget>[
                  TextButton(
                      onPressed: () {
                        DatePicker.showDateTimePicker(context,
                            showTitleActions: true, onChanged: (date) {
                          print('change $date');
                        }, onConfirm: (date) {
                          print('confirm $date');
                          if (mounted) {
                            setState(() {
                              jiChaDate = date.toString().substring(0, 19);
                            });
                          }
                        }, currentTime: DateTime.now(), locale: LocaleType.zh);
                      },
                      child: Container(
                        width: ScreenUtil().setHeight(400),
                        padding: EdgeInsets.fromLTRB(0, 10, 10, 10),
                        child: Text(
                          jiChaDate.length > 0 ? jiChaDate : '请选择',
                          style: TextStyle(
                              color: Color(0xFFB6B6B6),
                              fontSize: ScreenUtil().setSp(30)),
                        ),
                      )),
                ],
              ),
            ),
          ),
          Icon(
            Icons.keyboard_arrow_right,
            color: Color(0xff666666),
          )
        ],
      ),
    );
  }

  //稽查备注
  Widget getJiChaBeiZhu() {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            "稽查备注",
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(50),
          ),
          Expanded(
              flex: 1,
              child: Container(
                height: ScreenUtil().setWidth(160),
                width: ScreenUtil().setWidth(500),
                color: Color(0xfff2f5f9),
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(width: 1.0, color: Colors.black12),
                    borderRadius: BorderRadius.circular(2.5),
//                                               color: Colors.white,
                  ),
                  child: TextField(
                    textAlign: TextAlign.start,
                    maxLines: null,
                    onSubmitted: (text) {
                      //内容提交(按回车)的回调

                      print('submit $text');
                    },
                    controller: _jiChaTextEditingController,
                    textInputAction: TextInputAction.done,
                    decoration: InputDecoration(
//                                                 hintText: "请输入",
//                                                 hintStyle: TextStyle(fontSize: ScreenUtil().setSp(28.0)),
//                                                  enabledBorder: OutlineInputBorder(
//                                                    /*边角*/
//                                                    borderRadius: BorderRadius.all(
//                                                      Radius.circular(5), //边角为30
//                                                    ),
//                                                    borderSide: BorderSide(
//                                                      color: Colors.black12, //边线颜色为黄色
//                                                      width: 1.0, //边线宽度为2
//                                                    ),
//                                                  ),
                      fillColor: Color(0xfff2f5f9),
                      contentPadding: EdgeInsets.all(10.0),
                      border: InputBorder.none,
                    ),
                  ),
                ),
              )),
        ],
      ),
    );
  }

  Widget getRow(String str1, String str2) {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Text(
            str1 ?? '',
            style: TextStyle(
                color: Color(0xff666666), fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(40),
          ),
          Container(
            color: Colors.grey,
            height: ScreenUtil().setHeight(40),
            width: ScreenUtil().setWidth(2),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(20),
          ),
          Expanded(
            flex: 1,
            child: Text(
              str2 ?? '',
              style: TextStyle(
                  color: Color(0xff666666), fontSize: ScreenUtil().setSp(35)),
            ),
          ),
        ],
      ),
    );
  }

  Widget getPhoneRow(String str1, String str2) {
    return Container(
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Text(
            str1 ?? '',
            style: TextStyle(
                color: Color(0xff666666), fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(40),
          ),
          Container(
            color: Colors.grey,
            height: ScreenUtil().setHeight(40),
            width: ScreenUtil().setWidth(2),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(20),
          ),
          Expanded(
              flex: 1,
              child: GestureDetector(
                child: Container(
//                color: Colors.red,
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: Text(
                            str2 ?? '',
//                          maxLines: 2,
//                          overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                color: Color(0xff666666),
                                fontSize: ScreenUtil().setSp(35)),
                          ),
                        ),
                        Offstage(
                          offstage: str2 != "" ? false : true,
                          child: TextButton.icon(
                              onPressed: () {
                                _launchPhone(str2);
                              },
                              icon: Icon(Icons.phone_in_talk),
                              label: Text("呼叫")),
                        )
                      ],
                    )),
                onTap: () {
                  _launchPhone(str2);
                },
              )),
        ],
      ),
    );
  }

  _launchPhone(str) async {
    if (str != "" && str != null) {
      var url = 'tel:$str';
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        Fluttertoast.showToast(msg: "号码有误,不能拨打电话");
        throw 'Could not launch $url';
      }
    } else {
      Fluttertoast.showToast(msg: "号码有误,不能拨打电话");
    }
  }

  Future submitFile() async {
    List idenList = [];
    for (int i = 0; i < assets.length; i++) {
      File? file = await assets[i].file;

      //var fileType = file?.path.substring(file.path.lastIndexOf('.') + 1);

      idenList.add(file?.path);
    }
    List formDataArr =[];
    for (int i = 0; i < idenList.length; i++) {
      var name = idenList[i]
          .substring(idenList[i].lastIndexOf("/") + 1, idenList[i].length).toString()
          .replaceAll(" ", "");

      var fileData =
          await MultipartFile.fromFileSync(idenList[i], filename: name);

      formDataArr.add(fileData);
    }
    try {
      FormData formData = new FormData.fromMap({"files": formDataArr});

      print("formDataArr\n${formDataArr}");
      print("稽查上传formData\n${formData}");

      Response response = await Dio().post(
        WebConfig().jichaUrl + "method=upload_tp",
        data: formData,
        onSendProgress: (int sent, int total) {
          print("$sent $total");
        },
      );
      print(response.data);
      var jsonData = jsonDecode(response.data);
      if (jsonData["resultCode"] == "100") {
        submitInfo(jsonData["resultMsg"]);
      } else {
        if(mounted) {
          setState(() {
            isloading = true;
          });
        }
        Fluttertoast.showToast(msg: jsonData["resultMsg"]);
      }
    } catch (e) {
      print("cuowu:" + e.toString());
    }
  }

  Future submitInfo(String files) async {
    Response response = await Dio().get(WebConfig().jichaUrl +
        "method=add_jicha&ybbm=" +
        widget.checkListEntity!.ybbm! +
        "&jcr=" +sharedPreferences.getString("username")!+
        "&jcsj=" +
        jiChaDate +
        "&jcjg=" +
        chuLiJieGuo! +
        "&jcbz=" +
        _jiChaTextEditingController.text.toString() +
        "&files=" +
        files);
    print(response.requestOptions.path);
    print(response.data);
    Fluttertoast.showToast(msg: response.data["resultMsg"]);
    if(mounted) {
      setState(() {
        isloading = true;
      });
    }
    if(response.data["resultCode"]=="100") {
      Navigator.of(context).pop(true);
    }

  }
}
